"""定义JWT认证类"""

from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.conf import settings
import jwt
from jwt import exceptions


class JwtQueryParamsAuthentication(BaseAuthentication):
    def authenticate(self, request):
        # 获取Token并判断Token的合法性
        token = request.query_params.get("token")
        salt = settings.SECRET_KEY
        # 1.切割
        # 2.解密第二段/判断过期
        # 3.验证第三段合法性
        try:
            payload = jwt.decode(token, salt, algorithms=["HS256"])
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({"code": 1003, "error": "Token已经失效"})
        except exceptions.DecodeError:
            raise AuthenticationFailed({"code": 1004, "error": "Token认证失败啦！"})
        except exceptions.InvalidTokenError:
            raise AuthenticationFailed({"code": 1005, "error": "非法的Token"})

        # 三种操作
        # 1.抛出异常,后序不在执行.
        # 2.return-个元组(1,2),认证通过;在视图中如果调用request.user 就是元组的第一个值;request.auth
        # 3. None
        print(payload)
        return (payload, token)
